package com.vf.cloud.server.dispatch.pool;

import java.util.concurrent.ConcurrentHashMap;

import com.jfinal.plugin.activerecord.Db;
import com.vf.cloud.common.util.DateUtil;
import com.vf.cloud.pass.common.domain.biz.Terminal;
import com.vf.cloud.pass.common.domain.biz.TerminalGpu;
import com.vf.cloud.pass.common.factory.GPUFactory;

import io.netty.channel.ChannelHandlerContext;

public class DispatchPool {

	private static ConcurrentHashMap<String, ChannelHandlerContext> NODE_CLINET = new ConcurrentHashMap<String, ChannelHandlerContext>();
	private static ConcurrentHashMap<String, String> BRIDGE = new ConcurrentHashMap<String, String>();
	
	
	public static ConcurrentHashMap<String, ChannelHandlerContext> getNodes() {
		return NODE_CLINET;
	}

	public static void addNode(String key, ChannelHandlerContext ctx) {
		NODE_CLINET.put(key, ctx);
		BRIDGE.put(ctx.channel().id().asLongText(), key);
		
		Terminal terminal = Terminal.dao.findById(key);
		if (terminal != null) {
			terminal.setStatus("1");
			terminal.setOnlineTime(DateUtil.getLocalDateTime());
			terminal.update();
		}else {
			terminal=new Terminal();
			terminal.setId(key);
			terminal.setStatus("1");
			terminal.setOnlineTime(DateUtil.getLocalDateTime());
			terminal.save();
		}
		
	}
	
	public  static Terminal getNodeByChannelId(String channelId) {
		return Terminal.dao.findById(BRIDGE.get(channelId));
	}

	public static void removeNode(String channelId) {
		if (BRIDGE.containsKey(channelId)) {
			NODE_CLINET.remove(BRIDGE.get(channelId));
			Terminal terminal = Terminal.dao.findById(BRIDGE.get(channelId));
			if (terminal != null) {
				terminal.setStatus("0");
				terminal.setOfflineTime(DateUtil.getLocalDateTime());
				terminal.update();
			}
			Db.update("update "+TerminalGpu.TABLE_NAME+" set gpu_status='0' where terminal_id=?",BRIDGE.get(channelId));
			GPUFactory.getInstance().disconnected(BRIDGE.get(channelId));
			BRIDGE.remove(channelId);
			
		}
	}

}
